package cn.wind.xboot.logic.tools.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ZipUtil;
import cn.wind.xboot.logic.tools.dao.GenMapper;
import cn.wind.xboot.logic.tools.entity.TableInfo;
import cn.wind.xboot.logic.tools.service.IGenService;
import cn.wind.mybatis.generator.MyBatisPlusGenerator;
import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * 代码生成 服务层处理
 *
 * @author ruoyi
 */
@Service
public class GenServiceImpl implements IGenService<TableInfo> {
    @Autowired
    private GenMapper genMapper;
    @Value("${xboot.table.outputDir:}")
    private String outputDir;

    /**
     * 查询ry数据库表信息
     *
     * @param tableInfo 表信息
     * @return 数据库表列表
     */

    @Override
    public IPage<TableInfo> page(IPage<TableInfo> infoIPage,TableInfo tableInfo) {
        return genMapper.page(infoIPage,tableInfo);
    }
    /**
     * 生成代码
     *
     * @param tableName 表名称
     * @return 数据
     */
    @Override
    public byte[] generatorCode(String tableName) throws IOException{
           return  generator(new String[]{tableName});
    }

    /**
     * 批量生成代码
     *
     * @param tableNames 表数组
     * @return 数据
     */
    @Override
    public byte[] generatorCode(String[] tableNames)throws IOException{
        return  generator(tableNames);
    }
    @Resource
    private DruidDataSource druidDataSource;
    /**
     * 生成代码
     */
    public byte[] generator(String[] tableNames) {
        String uuid=UUID.randomUUID().toString();
        String path= outputDir + File.separator+uuid;
        String zipPath=outputDir+File.separator+uuid+".zip";
        MyBatisPlusGenerator.GeneratorDto generatorDto= MyBatisPlusGenerator.GeneratorDto.builder()
                .author("wind")
                .url(druidDataSource.getUrl())
                .username(druidDataSource.getUsername())
                .password(druidDataSource.getPassword())
                .type("com.mysql.jdbc.Driver")
                .outputDir(path)
                .packageName("cn.wind.xboot.logic")
                .entityLombokModel(true)
                .tableNames(tableNames)
                .baseResultMap(true)
                .build();
        MyBatisPlusGenerator generator=new MyBatisPlusGenerator();
        generator.generateByTables(generatorDto);
        File file=ZipUtil.zip(path,zipPath,true);
        return  FileUtil.readBytes(file);
    }
}
